import os, ConfigParser

__doc__ = """\
ChromeApp Library for Chromify
Created by G. John Schutte IV (SnohomaNET)

Most of this is private, to keep the API simple, while being able to
traceback errors more effectively.  Ideally you change nothing in this
file, rather you override the Hard-coded defaults with a configuration
file in /etc/ called chromify.conf.

"""

# Hard-coded Defaults, override with ../etc/chromify.conf
DEF_NAME = 0
DEF_ICON = "/usr/share/pixmaps/chrome.png"
DEF_BIN = "google-chrome"
DEF_COMMENT = "Google Chrome Web Application"
DEF_TMP_DIR = "/usr/share/chromify/"
DEF_TMP_FILE = "template.desktop"
DEF_WEBAPP_DIR = os.getenv("HOME") + "/.local/share/applications/"
DEF_USER_DIR = os.getenv("HOME") + "/.chromify/"
DEF_CONF = "/etc/chromify.conf"
DEF_CATEGORIES = "Network;WebBrowser"

class Application(object):
    def __init__(self, data):
        self.Template = self.__ImportTemplate(self.__AddSep(data["template_dir"]), self.__AddExtension(data["template_file"]))
        del data["template_dir"]
        del data["template_file"]
        self.Settings = data
        if not self.Template <= 0:
            self.Launcher = self.Template % self.Settings
        else:
            return -4
        self.CreationStatus = self.__CreateApplication(data["web_apps_dir"], data["id"], self.Launcher)

    def __CreateApplication(self, target_dir, target_file, target_data):
        if self.__Exists(target_dir) == 1:
            f = open(self.__AddSep(target_dir) + self.__AddExtension(str(target_file)), "w")
            f.write(target_data)
            f.close()
            os.chmod(self.__AddSep(target_dir) + self.__AddExtension(str(target_file)), 0755)
            s = "Created application '%s' in '%s' with data:\n\n%s" % (self.__AddExtension(target_file), self.__AddSep(target_dir), target_data)
        return s
    
    def __ImportTemplate(self, p, template):
        # Import Template file, and return as string object
        template = p + template
        if self.__Exists(template) == 2:
            f = open(template, "rb").read()
        else:
            # Error
            return -5
        return f
    
    def __AddSep(self, s):
        if not s.endswith("/"):
            s = s + "/"
        return s
    
    def __AddExtension(self, s):
        if not s.endswith(".desktop"):
            s = s + ".desktop"
        return s
    
    def __Exists(self, p):
        # Helper, checks if file/path exists
        # Returns 1 for Directory, 2 for File (0 for non-existent, -1 for error/special)
        if os.path.exists(p):
            if os.path.isdir(p):
                return 1
            elif os.path.isfile(p):
                return 2
            else:
                # ??
                return -9
        else:
            return 0
    
def ValidateConfig(conf):
    global DEF_NAME, DEF_COMMENT, DEF_ICON, DEF_TEMP_DIR, DEF_TEMP_FILE, DEF_BIN, DEF_WEBAPP_DIR, DEF_USER_DIR, DEF_CATEGORIES
    if conf is 0:
        conf = {}
    if conf is -1:
        conf = {}
    if not conf.has_key("name"):
        conf["name"] = DEF_NAME
    if not conf.has_key("comment"):
        conf["comment"] = DEF_COMMENT
    if not conf.has_key("icon"):
        conf["icon"] = DEF_ICON
    if not conf.has_key("id"):
        conf["id"] = conf["name"]
    if not conf.has_key("categories"):
        conf["categories"] = DEF_CATEGORIES
    if not conf.has_key("template_dir"):
        conf["template_dir"] = DEF_TEMP_DIR
    if not conf.has_key("template_file"):
        conf["template_file"] = DEF_TEMP_FILE
    if not conf.has_key("chrome_bin"):
        conf["execute"] = DEF_BIN
    if not conf.has_key("web_apps_dir"):
        conf["web_apps_dir"] = DEF_WEBAPP_DIR
    if not conf.has_key("user_dir"):
        conf["user_dir"] = DEF_USER_DIR
    return conf

def GetConfigOptions():
    # Get a conf file, and its options.
    c = {}
    if os.path.exists(DEF_CONF):
        # Import configuration file, and populate into Dictionary
        conf = ConfigParser.ConfigParser()
        conf.read(DEF_CONF)
        if conf.has_section("DEFAULTS"):
            for i in conf.items("DEFAULTS"):
                c[i[0]] = i[1]
        else:
            # Error, no DEFAULTS section in conf...
            c = -6
    else:
        # No Configuration file available
        c = -7
    
    return c
